import random
from collections import Counter

def topKFrequent(nums, k):
    count = Counter(nums)
    freq_list = list(count.items())

    def partition(left, right, pivot_index):
        pivot_freq = freq_list[pivot_index][1]
        freq_list[pivot_index], freq_list[right] = freq_list[right], freq_list[pivot_index]
        store_index = left
        for i in range(left, right):
            if freq_list[i][1] > pivot_freq:
                freq_list[store_index], freq_list[i] = freq_list[i], freq_list[store_index]
                store_index += 1
        freq_list[store_index], freq_list[right] = freq_list[right], freq_list[store_index]
        return store_index

    def quickselect(left, right, k_smallest):
        if left == right:
            return
        pivot_index = random.randint(left, right)
        index = partition(left, right, pivot_index)
        if index == k_smallest:
            return
        elif index < k_smallest:
            quickselect(index + 1, right, k_smallest)
        else:
            quickselect(left, index - 1, k_smallest)

    n = len(freq_list)
    quickselect(0, n - 1, k - 1)
    return [num for num, freq in freq_list[:k]]
